package com.bbcare.img.plat.service.impl;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ToolUtil;
import com.bbcare.img.plat.entity.AiEquipClassDict;
import com.bbcare.img.plat.entity.AiImg;
import com.bbcare.img.plat.service.IAddPhotoService;
import com.bbcare.img.plat.store.ibatis.IEquipClassDAO;
import com.bbcare.img.plat.store.ibatis.IEquipDAO;
import com.bbcare.img.plat.store.ibatis.IIaOperationRecordDAO;
import com.bbcare.img.plat.store.ibatis.IImgDAO;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @name: 图片用户关联接口实现
 * @author: wuyz
 * @createTime: 2017.11.02
 * @description: 图片用户关联等
 * @modify:
 *
 */
@Service
public class AddPhotoServiceImpl implements IAddPhotoService {
    private final Log logger = LogFactory.getLog(AddPhotoServiceImpl.class);

    @Autowired
    private IImgDAO imgDao;

    @Autowired
    private IIaOperationRecordDAO iaOperationRecordDao;

    @Autowired
    private IEquipClassDAO equipClassDao;

    @Autowired
    private IEquipDAO equipDao;

    // 用户和图片或者视屏关联实现方法
    @Override
    @Transactional
    public Map<String, Object> correlationUser(Map<String, Object> mapIn) throws Exception {
        logger.info("correlationUser : " + mapIn.toString());
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> argMap = new HashMap<String, Object>();
        Map<String, Object> sessionInfo = ToolUtil.typeCast(mapIn.get("sessionInfo"));
        Map<String, Object> oprInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        Map<String, Object> assInfo = ToolUtil.typeCast(mapIn.get("assInfo"));

        String tenantId ="";
        String authorId ="";
        if(sessionInfo!=null && sessionInfo.size()>0) {
        	tenantId = (String) sessionInfo.get("tenantId");// 租户
            authorId = (String) sessionInfo.get("authorId");// 作者
        }else {
        	tenantId = (String) mapIn.get("tenantId");// 租户
            authorId = (String) mapIn.get("authorId");// 作者
        }


        String birthday = (String) assInfo.get("birthday");// 患者生日
        String gender = (String) assInfo.get("gender");// 患者性别
        List<String> imgIdList = ToolUtil.typeCast(assInfo.get("imgIdList"));// 文件id
        String residentAddress = (String) assInfo.get("residentAddress");// 患者居住地址
        String userId = (String) assInfo.get("userId");// 患者id
        String updateTime = (String) oprInfo.get("updateTime");// 更新时间
        String updateAccept = (String) oprInfo.get("updateAccept");// 更新流水
        String queueId = (String) assInfo.get("queueId");// 队列id


        if (CollectionUtils.isEmpty(imgIdList)) {
            throw (new AppException(ErrorCode.IMG_EXCEPTION_EQUIP_HAS_ALREADY_EXISTS, "文件id为空"));
        }

        Map<String, Object> qryMapIn = new HashMap<String, Object>();
        List<String> imgIdListNew = new ArrayList<String>();
        List<AiImg> aiImgList = null;
        String currUserId = "";
        // 查询是否已经绑定过且绑定的患者是同一个人
        for (String imgId : imgIdList) {
            qryMapIn.put("id", imgId);
            aiImgList = imgDao.listImgByCondition(qryMapIn);
            if (CollectionUtils.isNotEmpty(aiImgList)) {
                currUserId = aiImgList.get(0).getUserId();
                if (StringUtils.isNotBlank(currUserId) && !currUserId.equals(userId)) {
                    logger.info("该文件【" + aiImgList.get(0).getSourceFileName() + "】已绑定其他患者，无法绑定当前患者！");
                } else if (StringUtils.isBlank(currUserId)) {
                    imgIdListNew.add(imgId);
                }
            }
        }
        if (CollectionUtils.isEmpty(imgIdListNew)) {
            return mapOut;
        }

        // 图片或者视频关联用户
        argMap.put("queueId", queueId);
        argMap.put("birthday", birthday);
        argMap.put("gender", gender);
        argMap.put("residentAddress", residentAddress);
        argMap.put("userId", userId);
        argMap.put("imgIdList", imgIdListNew);
        argMap.put("updateTime", updateTime);
        argMap.put("updateAccept", updateAccept);
        argMap.put("updateAuthor", authorId);
        argMap.put("updateType", Constants.UPDATE_TYPE_INSERT);
        imgDao.updateAiImgInfoUser(argMap);// 在更新入正表
        imgDao.saveAiImgHisByIdList(argMap);// 先入历史表

        // 操作记录
        Map<String, Object> paramRecord = new HashMap<String, Object>();
        Calendar now = Calendar.getInstance();
        paramRecord.put("month", String.valueOf(now.get(Calendar.MONTH) + 1));
        paramRecord.put("day", String.valueOf(now.get(Calendar.DAY_OF_MONTH)));
        paramRecord.put("userId", userId);
        paramRecord.put("queueId", "");
        paramRecord.put("opUser", authorId);
        paramRecord.put("opTime", updateTime);
        paramRecord.put("remark", oprInfo.get("opNote"));
        paramRecord.put("busiCategory", Constants.DOCTOR_ACTIVE_BUSI_TYPE_10);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_BG_ADMIN);
        paramRecord.put("id", updateAccept);
        paramRecord.put("opDesc", oprInfo.get("opNote"));
        paramRecord.put("opCode", oprInfo.get("opCode"));
        paramRecord.put("busiId", null);
        paramRecord.put("tenantId", tenantId);
        paramRecord.put("opType", oprInfo.get("opType"));
        paramRecord.put("taskId", "");
        paramRecord.put("breifIntro", "");
        iaOperationRecordDao.saveOperationRecord(paramRecord);

        return mapOut;
    }

    // 根据问卷内容中配置的设备类型查询当前需要检索文件的设备列表
    @Override
    public Map<String, Object> queryEquipByClassId(Map<String, Object> mapIn) throws Exception {
        Map<String, Object> mapOut = new HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Object> classIdList = ToolUtil.typeCast(mapIn.get("classIdList"));// 文件id
        if (CollectionUtils.isEmpty(classIdList)) {
            throw (new AppException(ErrorCode.IMG_EXCEPTION_EQUIP_HAS_ALREADY_EXISTS, "设备类型list为空"));
        }

        List<AiEquipClassDict> listDict = equipClassDao.listEquipClassGroup(mapIn);
        for (int i = 0; i < listDict.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("classId", listDict.get(i).getId());
            map.put("tenantId", mapIn.get("tenantId"));
            List<Map<String, Object>> listEquip = equipDao.listEquipByClassId(map);
            if (CollectionUtils.isEmpty(listEquip)) {
                continue;
            }
            map.put("className", listDict.get(i).getClassName());
            map.put("equipList", listEquip);
            list.add(map);
        }
        mapOut.put("classList", list);
        return mapOut;
    }

    // 根据相关条件查询影像文件 注意：一张影像文件只能被一个患者关联，同一张影像文件不可能属于两个人
    @Override
    public Map<String, Object> queryImg(Map<String, Object> mapIn) throws Exception {
        Map<String, Object> mapOut = new HashMap<String, Object>();
        List<AiImg> list = new ArrayList<AiImg>();
        List<Object> equipIdList = ToolUtil.typeCast(mapIn.get("equipIdList"));// 文件id
        if (CollectionUtils.isEmpty(equipIdList)) {
            mapIn.put("equipIdList", null);
        }
        // 查询当前条件下影像的文件的条数
        int total = 0;
        total = imgDao.listImgByequipIdListTotle(mapIn);
        if (total > 0) {
            list = imgDao.listImgByequipIdListAll(mapIn);
        }
        // 查询当前条件下具体影像文件的具体信息
        mapOut.put("total", total);
        mapOut.put("rows", list);

        return mapOut;
    }

    // 将图片与患者关联关系解除
    @Override
    @Transactional
    public Map<String, Object> removeAssImgUser(Map<String, Object> mapIn) throws Exception {
        logger.info("removeAssImgUser : " + mapIn.toString());
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> argMap = new HashMap<String, Object>();
        Map<String, Object> sessionInfo = ToolUtil.typeCast(mapIn.get("sessionInfo"));
        Map<String, Object> oprInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        Map<String, Object> assInfo = ToolUtil.typeCast(mapIn.get("assInfo"));
        String tenantId = (String) sessionInfo.get("tenantId");// 租户
        String authorId = (String) sessionInfo.get("authorId");// 作者
        String imgId = (String) assInfo.get("imgId");// 患者生日
        String userId = (String) assInfo.get("userId");// 患者性别
        String updateTime = (String) oprInfo.get("updateTime");// 更新时间
        String updateAccept = (String) oprInfo.get("updateAccept");// 跟新流水

        // 图片或者视屏关联用户
        argMap.put("birthday", null);
        argMap.put("gender", "");
        argMap.put("residentAddress", "");
        argMap.put("userId", "");
        argMap.put("OldUserId", userId);
        argMap.put("imgId", imgId);
        argMap.put("updateTime", updateTime);
        argMap.put("updateAccept", updateAccept);
        argMap.put("updateType", Constants.UPDATE_TYPE_INSERT);
        imgDao.saveAiImgHis(argMap);// 先入历史表
        imgDao.updateAiImgInfoUser(argMap);// 在跟新入正表

        // 操作记录
        Map<String, Object> paramRecord = new HashMap<String, Object>();
        Calendar now = Calendar.getInstance();
        paramRecord.put("month", String.valueOf(now.get(Calendar.MONTH) + 1));
        paramRecord.put("day", String.valueOf(now.get(Calendar.DAY_OF_MONTH)));
        paramRecord.put("userId", userId);
        paramRecord.put("queueId", "");
        paramRecord.put("opUser", authorId);
        paramRecord.put("opTime", updateTime);
        paramRecord.put("remark", oprInfo.get("opNote"));
        paramRecord.put("busiCategory", Constants.DOCTOR_ACTIVE_BUSI_TYPE_10);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_BG_ADMIN);
        paramRecord.put("id", updateAccept);
        paramRecord.put("opDesc", oprInfo.get("opNote"));
        paramRecord.put("opCode", oprInfo.get("opCode"));
        paramRecord.put("busiId", null);
        paramRecord.put("tenantId", tenantId);
        paramRecord.put("opType", oprInfo.get("opType"));
        paramRecord.put("taskId", "");
        paramRecord.put("breifIntro", "");
        iaOperationRecordDao.saveOperationRecord(paramRecord);

        return mapOut;
    }

	@Override
	public Map<String, Object> selectImgUser(Map<String, Object> mapIn) throws Exception {
		 Map<String, Object> mapOut = new HashMap<String, Object>();
	        List<AiImg> list = new ArrayList<AiImg>();
	        // 查询当前条件下影像的文件的条数
	        int total = 0;
	        total = imgDao.listImgListTotle(mapIn);
	        if (total > 0) {
	            list = imgDao.listImgByequipIdList(mapIn);
	        }
	        // 查询当前条件下具体影像文件的具体信息
	        mapOut.put("total", total);
	        mapOut.put("rows", list);
	        return mapOut;
	}

}
